﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoTestCommunication_Service
{
    class CRCcheck
    {
        public static bool CRCCheck(byte[] buffer)
        {
            int reCRC = CRC16(buffer, 0, buffer.Length - 2);//公式法
            int crcHi1 = (Byte)(reCRC % 256);
            int crcLo1 = (Byte)(reCRC / 256);
            if (buffer.Length >= 2)
            {
                if ((crcHi1 == buffer[buffer.Length - 2]) & (crcLo1 == buffer[buffer.Length - 1]))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public static int CRC16(byte[] Data, int start, int size)
        {
            byte CRC16Lo, CRC16Hi;       //CRC寄存器
            byte CL, CH;                   //多项式码&HA001
            byte SaveHi, SaveLo;
            int i, Flag;
            int CRC16_A;
            CRC16Lo = 0xFF;
            CRC16Hi = 0xFF;
            CL = 0x1;
            CH = 0xA0;
            for (i = 0; i <= size - 1; i++)
            {
                CRC16Lo = Convert.ToByte(CRC16Lo ^ Data[start + i]);         //每一个数据与CRC寄存器进行异或
                for (Flag = 0; Flag <= 7; Flag++)
                {
                    SaveHi = CRC16Hi;
                    SaveLo = CRC16Lo;
                    CRC16Hi = Convert.ToByte(CRC16Hi / 2);                 //高位右移一位
                    CRC16Lo = Convert.ToByte(CRC16Lo / 2);                 //低位右移一位

                    if ((SaveHi & 0x1) == 0x1)//如果高位字节最后一位为1
                    {
                        CRC16Lo = Convert.ToByte(CRC16Lo | 0x80);//则低位字节右移后前面补1

                    }
                    if ((SaveLo & 0x1) == 0x1)//如果LSB为1，则与多项式码进行异或
                    {
                        CRC16Hi = Convert.ToByte(CRC16Hi ^ CH);
                        CRC16Lo = Convert.ToByte(CRC16Lo ^ CL);
                    }
                }
            }

            CRC16_A = CRC16Hi;           //CRC高位
            CRC16_A = CRC16_A * 256;
            CRC16_A = CRC16_A + CRC16Lo;          //CRC低位
            return CRC16_A;
        }

    }
}
